package com.originit.order.server.controller;

import com.originit.order.server.converter.OrderConverter;
import com.originit.order.server.dto.OrderDTO;
import com.originit.order.server.enums.ResultEnum;
import com.originit.order.server.exception.OrderException;
import com.originit.order.server.form.OrderCreateForm;
import com.originit.order.server.service.OrderService;
import com.originit.order.server.util.DataUtil;
import com.originit.order.server.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Map;

@Api("订单接口")
@RestController
@RequestMapping("/order")
@Slf4j
@RefreshScope
public class OrderController {

    @Value("${hello}")
    private String hello;

    @RequestMapping("/hello")
    public  String hell(){
        return hello;
    }

    @Autowired
    OrderService orderService;

    @ApiOperation("创建订单")
    @PostMapping
    public ResultVO<Map<String,String>> create(@Valid OrderCreateForm form, BindingResult bindingResult){
        // 1. 校验
        if (bindingResult.hasErrors()) {
            log.error("【创建订单】参数不正确，orderForm={}",form);
            throw new OrderException(ResultEnum.PARAM_ERROR,bindingResult.getFieldError().getDefaultMessage());
        }
        // 2. 从校验实体转换为逻辑实体，供服务层的使用
        OrderDTO orderDTO = OrderConverter.orderCreateForm2OrderDTO(form);
        if (CollectionUtils.isEmpty(orderDTO.getDetailList())){
            log.error("【创建订单】购物车为空，detailList={}",orderDTO.getDetailList());
            throw new OrderException(ResultEnum.PARAM_ERROR,"购物车不能为空");
        }
        // 创建订单
        orderDTO = orderService.create(orderDTO);

        return ResultVO.success(DataUtil.<String,String>mapBuilder().append("orderId",orderDTO.getOrderId()).build());
    }

}
